/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

import dbUtil.*;
import iteradores.*;
import beans.*;
import utils.MD5;

/**
 *
 * @author Administrador
 */
public class ManejadorRetiroDevolucion extends HttpServlet {

    private String nombreModulo = "retirodevolucion";
    private IteradorUsuario usuarioActual;

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("windows-1252");
        PrintWriter out = response.getWriter();
        String url = "";

        try {
            Connection con = null;
            //Obtiene la operación a realizar 
            String str_op = request.getParameter("op");

            //Datos del solicitudregistro actual de la sesion, si esto es nulo significa
            //que aun no hizo login
            usuarioActual = (IteradorUsuario) request.getSession().getAttribute("usuarioActual");

            if (usuarioActual == null) {
                url = "login.jsp"; //Volver a loguearse
            } else {
                // Obtiene la conexión a la base de datos de la sesión
                con = (Connection) request.getSession().getAttribute("ConexionBd");

                //Objeto que averigua si el solicitudregistro tiene permiso para acceder al servlet.
                PgAbm testPermiso = new PgAbm();
                testPermiso.setCon(con);

                usuarioActual.getReset();
                usuarioActual.getNext();

                if (testPermiso.tienePermiso(nombreModulo,
                        usuarioActual.getNombreusuario(),
                        str_op.substring(0, 6))) {

                    String action = request.getParameter("action");

                    action = action == null ? "" : action;

                    url = "retirodevolucion.jsp?modo=SELECT";

                    if (str_op.equals("SELECT")) {
                        url = this.select_data(con, request, response, str_op);
                    } else if (str_op.equals("RETIRO") && action.equals("do")) {
                        url = this.update_data(con, request, response, str_op);
                    } else if (str_op.equals("DEVOLU") && action.equals("do")) {
                        url = this.update_data(con, request, response, str_op);
                    }
                } else {
                    url = "sinpermiso.jsp";
                }
            }
            mostrar_pagina(url, request, response);
        } catch (Exception e) {
            e.printStackTrace(out);
        }

    }

    public void mostrar_pagina(String url, HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        RequestDispatcher disp = req.getRequestDispatcher(url);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setCharacterEncoding("windows-1252");
        resp.setHeader("Pragma", "no-cache");
        resp.setIntHeader("Expires", 0);
        disp.forward(req, resp);
    }

    public DBConfig getDataBaseConfig() {
        ServletContext scon = getServletContext();
        DBConfig dc = new DBConfig();
        dc.setDbname(scon.getInitParameter("dbname"));
        dc.setServer(scon.getInitParameter("dbserver"));
        dc.setUser(scon.getInitParameter("dbuser"));
        dc.setPass(scon.getInitParameter("dbpass"));
        return dc;
    }
//<editor-fold defaultstate="collapsed" desc="Métodos ABM (SELECT, INSERT, UPDATE y DELETE).">
    public String select_data(
            Connection con, HttpServletRequest request, HttpServletResponse response, String operacion) throws Exception {
        String url = "retirodevolucion.jsp?modo=SELECT";
        String sql = "";
        Statement stm;
        Statement stm2;

        con.setAutoCommit(false);

        sql = "select r.idreserva, r.fechainicio, r.horainicio, r.fechafinal, r.horafinal, r.ubicacion, r.estado, " +
                " r.observacion, r.idusuario, u.nombreoperativo as solicitante,  r.idsolicitudreserva, r.idaprobador, " +
                " uapr.nombreoperativo as aprobador" +
                " from reserva r " +
                "     join usuario u on r.idusuario = u.idusuario" +
                "     join recurso re on r.idrecurso = re.idrecurso" +
                "     left outer join solicitudreserva sr on r.idsolicitudreserva = sr.idsolicitudreserva" +
                "     join usuario uapr on r.idaprobador = uapr.idusuario " +
                "     join tiporecurso tr on r.idtiporecurso = tr.idtiporecurso and tr.movil = true" +
                " where r.estado = 'A' " +
                " and idreserva not in (select idreserva from evento) " +
                " order by fechainicio";


        stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_READ_ONLY);

        System.out.println(sql);
        ResultSet result = stm.executeQuery(sql);
        IteradorReserva mp = new IteradorReserva(result);
        request.setAttribute("ReservasRetirar", mp);

        sql = "select r.idreserva, r.fechainicio, r.horainicio, r.fechafinal, r.horafinal, r.ubicacion, r.estado, " +
                " r.observacion, r.idusuario, u.nombreoperativo as solicitante,  r.idsolicitudreserva, r.idaprobador, " +
                " uapr.nombreoperativo as aprobador" +
                " from reserva r " +
                "     join usuario u on r.idusuario = u.idusuario" +
                "     join recurso re on r.idrecurso = re.idrecurso" +
                "     left outer join solicitudreserva sr on r.idsolicitudreserva = sr.idsolicitudreserva" +
                "     join usuario uapr on r.idaprobador = uapr.idusuario " +
                "     join tiporecurso tr on r.idtiporecurso = tr.idtiporecurso and tr.movil = true" +
                " where r.estado = 'R' " +
                " order by fechainicio";


        stm2 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_READ_ONLY);

        System.out.println(sql);
        ResultSet result2 = stm2.executeQuery(sql);
        IteradorReserva mp2 = new IteradorReserva(result2);
        request.setAttribute("ReservasDevolver", mp2);
        
        url += "&msg=SHOW";

        return url;
    }

    public String update_data(
            Connection con, HttpServletRequest request, HttpServletResponse response, String operacion) throws Exception {
        String url = "retirodevolucion.jsp?modo=SELECT";
        String sql = "";
        Statement stm;

        String action = request.getParameter("action");
        String estado = operacion.equals("RETIRO") ? "Retiro" : "Devolución";
        String msg = operacion.equals("RETIRO") ? "R" : "D";

        if ((action != null) && action.equalsIgnoreCase("do")) {
            con.setAutoCommit(false);

            ResultSet rs_datos = null;

            try {
                CallableStatement proc = con.prepareCall("{? = call ins_evento ( " +
                        "?, ?, ? ) }",
                        ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

                proc.registerOutParameter(1, Types.OTHER);
                proc.setInt(2, request.getParameter("idreserva").equals("") ? null : Integer.parseInt(request.getParameter("idreserva")));
                proc.setString(3, estado.equals("") ? null : estado);
                proc.setString(4, msg.equals("") ? null : msg);
                
                
                proc.execute();

                rs_datos = (ResultSet) proc.getObject(1);

                int cant_filas = 0;
                if (rs_datos.last()) {
                    cant_filas = rs_datos.getRow();
                    rs_datos.beforeFirst();
                }

                this.select_data(con, request, response, operacion);
                
                con.commit();

                url = "retirodevolucion.jsp?modo=SELECT&msg="+ msg + "DONE";
            } catch (SQLException ex) {
                request.setAttribute("error", ex.getMessage());
                System.out.println(ex.getMessage());
                url = "retirodevolucion.jsp?modo=" + operacion +"&msg=ERROR";
                con.rollback();
                this.select_data(con, request, response, operacion);
            }

        } else {
            this.select_data(con, request, response, operacion);
        }
        
        return url;
    }
//</editor-fold>
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    @Override
    public void destroy() {
    }

    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     */
    @Override
    public String getServletInfo() {
        return "Este servlet maneja las peticiones sobre la tabla SolicitudRegistro";
    }
// </editor-fold>
}
